package com.ruoyi.manage.enterprise.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.ObjUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StrUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.manage.enterprise.domain.EcEnterpriseInformation;
import com.ruoyi.manage.enterprise.domain.EcEnterpriseParams;
import com.ruoyi.manage.enterprise.domain.EnterpriseUser;
import com.ruoyi.manage.enterprise.domain.SysUserExpand;
import com.ruoyi.manage.enterprise.domain.vo.EcEnterpriseInformationVo;
import com.ruoyi.manage.enterprise.service.IEcEnterpriseInformationService;
import com.ruoyi.manage.enterprise.service.ISysUserExpandService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 企业管理Controller
 *
 * @author ruoyi
 * @date 2025-07-27
 */
@Api(tags = "企业管理控制器")
@RestController
@RequestMapping("/manage/enterprise")
public class EcEnterpriseInformationController extends BaseController {
    /**
     * 配置表别名 默认空
     */
    private final static String TABLE_PREFIX = StrUtil.initTableAlias(null);
    @Autowired
    private IEcEnterpriseInformationService ecEnterpriseInformationService;

    @Autowired
    private ISysUserExpandService iSysUserExpandService;

    /**
     * 查询企业管理列表
     */
    @ApiOperation(value = "查询企业管理", notes = "企业管理管理")
    @PreAuthorize("@ss.hasPermi('manage:enterprise:list')")
    @GetMapping("/list")
    public TableDataInfo list(EcEnterpriseInformationVo ecEnterpriseInformation, QueryWrapper<EcEnterpriseInformation> queryWrapper) {
        setQueryCondition(ecEnterpriseInformation, queryWrapper);
        startPage();
        List<EcEnterpriseInformation> list = ecEnterpriseInformationService.list(queryWrapper);
        return getDataTable(list);
    }

    private void setQueryCondition(EcEnterpriseInformationVo ecEnterpriseInformation, QueryWrapper<EcEnterpriseInformation> queryWrapper) {
        if (StrUtil.isNotBlank(ecEnterpriseInformation.getEnterpriseName())) {
            queryWrapper.like(TABLE_PREFIX + "enterprise_name", ecEnterpriseInformation.getEnterpriseName());
        }
        if (StrUtil.isNotBlank(ecEnterpriseInformation.getExamineResult())) {
            queryWrapper.eq("examine_result", ecEnterpriseInformation.getExamineResult());
        }
        if (ObjUtil.isNotNull(ecEnterpriseInformation.getCreateTimeRange()) && ecEnterpriseInformation.getCreateTimeRange().length > 1) {
            String[] createTimeRange = ecEnterpriseInformation.getCreateTimeRange();
            queryWrapper.between("create_time", createTimeRange[0], createTimeRange[1]);
        }
        if (StrUtil.isNotBlank(ecEnterpriseInformation.getProvinceSiteId())) {
            queryWrapper.eq("province_site_id", ecEnterpriseInformation.getProvinceSiteId());
        }
        if (StrUtil.isNotBlank(ecEnterpriseInformation.getCitySiteId())) {
            queryWrapper.eq("city_site_id", ecEnterpriseInformation.getCitySiteId());
        }
        if (StrUtil.isNotBlank(ecEnterpriseInformation.getAreaSiteId())) {
            queryWrapper.eq("area_site_id", ecEnterpriseInformation.getAreaSiteId());
        }
        if (StrUtil.isNotBlank(ecEnterpriseInformation.getRealNameFlag())) {
            queryWrapper.eq("real_name_flag", ecEnterpriseInformation.getRealNameFlag());
        }
        if(StrUtil.isNotBlank(ecEnterpriseInformation.getAuthenticationFlag())){
            queryWrapper.eq("authentication_flag",ecEnterpriseInformation.getAuthenticationFlag());
        }
        if (StrUtil.isNotBlank(ecEnterpriseInformation.getCreditCode())) {
            queryWrapper.eq(TABLE_PREFIX + "credit_code", ecEnterpriseInformation.getCreditCode());
        }
        queryWrapper.orderByDesc(TABLE_PREFIX + "create_time");
    }


    @GetMapping("/getEnterpriseByUser")
    public AjaxResult getEnterpriseByUser(EcEnterpriseParams params) {
        List<EcEnterpriseInformation> list = ecEnterpriseInformationService.selectEnterpriseByUserId(params);
        return AjaxResult.success(list);
    }

    @GetMapping("/enterpriseUser")
    public TableDataInfo enterpriseUser(EnterpriseUser user, QueryWrapper<EnterpriseUser> queryWrapper) {

        if (StrUtil.isNotBlank(user.getNickName())) {
            queryWrapper.like("u.nick_name", user.getNickName());
        }
        if (StrUtil.isNotBlank(user.getMobile())) {
            queryWrapper.eq("u.phonenumber", user.getMobile());
        }
        if (ObjUtil.isNotNull(user.getStatus())) {
            queryWrapper.eq("u.status", user.getStatus());
        }
        if (ObjUtil.isNotNull(user.getCreateTimeRange()) && user.getCreateTimeRange().length == 2) {
            String[] timeRange = user.getCreateTimeRange();
            queryWrapper.between("u.create_time", timeRange[0], timeRange[1]);
        }


        startPage();
        queryWrapper.eq("u.user_type", 0);
        queryWrapper.groupBy("u.user_id");
        List<EnterpriseUser> enterpriseUsers = iSysUserExpandService.selectEnterpriseUser(queryWrapper);
        return getDataTable(enterpriseUsers);
    }

    /**
     * 导出企业管理列表
     */
    @PreAuthorize("@ss.hasPermi('manage:enterprise:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, EcEnterpriseInformationVo ecEnterpriseInformation, QueryWrapper<EcEnterpriseInformation> queryWrapper) {
        if (CollUtil.isEmpty(ecEnterpriseInformation.getIds())) {
            setQueryCondition(ecEnterpriseInformation, queryWrapper);
        } else {
            queryWrapper.in(TABLE_PREFIX + "id", ecEnterpriseInformation.getIds());
        }
        List<EcEnterpriseInformation> list = ecEnterpriseInformationService.list(queryWrapper);
        ExcelUtil<EcEnterpriseInformation> util = new ExcelUtil<EcEnterpriseInformation>(EcEnterpriseInformation.class);
        util.exportExcel(response, list, "enterprise");
    }

    /**
     * 获取企业管理详细信息
     */
    @ApiOperation(value = "获取企业管理", notes = "企业管理管理")
    @PreAuthorize("@ss.hasPermi('manage:enterprise:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(ecEnterpriseInformationService.queryGetById(id));
    }

    /**
     * 获取企业管理详细信息
     */
    @ApiOperation(value = "获取企业管理", notes = "企业管理管理")
    @GetMapping(value = "/moreInfo/{id}")
    public AjaxResult getMoreInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(ecEnterpriseInformationService.queryMoreGetById(id));
    }

    /**
     * 新增企业管理
     */
    @ApiOperation(value = "新增企业管理", notes = "企业管理管理")
    @PreAuthorize("@ss.hasPermi('manage:enterprise:add')")
    @RepeatSubmit
    @PostMapping
    public AjaxResult add(@Validated @RequestBody EcEnterpriseInformation ecEnterpriseInformation) {
        return toAjax(ecEnterpriseInformationService.addEcEnterpriseInformation(ecEnterpriseInformation) ? 1 : 0);
    }

    /**
     * 企业认证新增
     */

    @PostMapping("/addCertification")
    @RepeatSubmit
    public AjaxResult addCertification(@RequestBody EcEnterpriseInformationVo ecEnterpriseInformationVo) {
        return toAjax(ecEnterpriseInformationService.addEcEnterpriseCertification(ecEnterpriseInformationVo));
    }

    /**
     * 企业认证修改
     */

    @PutMapping("/updateCertification")
    @RepeatSubmit
    public AjaxResult updateEnterpriseCertification(@RequestBody EcEnterpriseInformationVo ecEnterpriseInformationVo) {
        return toAjax(ecEnterpriseInformationService.updateEnterpriseCertification(ecEnterpriseInformationVo));
    }

    /**
     * 企业认证修改
     */

    @GetMapping("/swithMainSign")
    @RepeatSubmit
    public AjaxResult swithMainSign(@Param("creditCode") String creditCode) {
        iSysUserExpandService.lambdaUpdate().set(SysUserExpand::getMainSign,"0").eq(SysUserExpand::getUserId, SecurityUtils.getUserId()).update();
        iSysUserExpandService.lambdaUpdate().set(SysUserExpand::getMainSign,"1").eq(SysUserExpand::getEnterpriseCreditCode,creditCode).update();
        return AjaxResult.success();
    }

    /**
     * 修改企业管理
     */
    @ApiOperation(value = "修改企业管理", notes = "企业管理管理")
    @PreAuthorize("@ss.hasPermi('manage:enterprise:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody EcEnterpriseInformation ecEnterpriseInformation) {
        return toAjax(ecEnterpriseInformationService.updateEcEnterpriseInformation(ecEnterpriseInformation) ? 1 : 0);
    }

    /**
     * 修改企业管理
     */
    @ApiOperation(value = "审核企业管理", notes = "审核管理管理")
    @PreAuthorize("@ss.hasPermi('manage:enterprise:edit')")
    @PutMapping("/check")
    public AjaxResult check(@RequestBody EcEnterpriseInformation ecEnterpriseInformation) {
        return toAjax(ecEnterpriseInformationService.checkEcEnterpriseInformation(ecEnterpriseInformation) ? 1 : 0);
    }

    /**
     * 删除企业管理
     */
    @ApiOperation(value = "删除企业管理", notes = "企业管理管理")
    @PreAuthorize("@ss.hasPermi('manage:enterprise:remove')")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(ecEnterpriseInformationService.deleteEcEnterpriseInformationByIds(ids) ? 1 : 0);
    }
}
